package com.mcr.graduateprogram.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mcr.graduateprogram.bean.Manager;
import com.mcr.graduateprogram.mapper.ManagerMapper;
import com.mcr.graduateprogram.service.IManagerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author graduateprogram
 * @since 2023-02-25
 */
@Service
public class ManagerServiceImpl extends ServiceImpl<ManagerMapper, Manager> implements IManagerService {
    @Autowired
    private ManagerMapper managerMapper;

    @Override
    public Page<Manager> getPage(Integer page, Integer pageSize, String name) {
        Page<Manager> managerPage=new Page<>(page,pageSize);
        LambdaQueryWrapper<Manager> managerLambdaQueryWrapper=new LambdaQueryWrapper<>();
        managerLambdaQueryWrapper.like(name!=null,Manager::getName,name);
        managerMapper.selectPage(managerPage, managerLambdaQueryWrapper);
        return managerPage;
    }

    @Override
    public boolean addManager(Manager manager) {
        List<Manager> managerList = checkName(manager);
        if(managerList.size()==0){
            managerMapper.insert(manager);
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean updateManagerById(Manager manager) {
        List<Manager> managerList = checkName(manager);
        int count=managerList.size();
        if(count==0){
            managerMapper.updateById(manager);
            return true;
        }else if(count==1&&managerList.get(0).getId().longValue()==manager.getId().longValue()){
            managerMapper.updateById(manager);
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Manager login(Manager manager) {
        LambdaQueryWrapper<Manager> managerLambdaQueryWrapper=new LambdaQueryWrapper<>();
        managerLambdaQueryWrapper.eq(Manager::getName,manager.getName())
                         .eq(Manager::getPassword,manager.getPassword());
        return managerMapper.selectOne(managerLambdaQueryWrapper);
    }

    private List<Manager> checkName(Manager manager){
        LambdaQueryWrapper<Manager> managerLambdaQueryWrapper=new LambdaQueryWrapper<>();
        managerLambdaQueryWrapper.eq(Manager::getName,manager.getName());
        return managerMapper.selectList(managerLambdaQueryWrapper);
    }
}
